﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Management;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace COMPortStatusTest
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        Dictionary<string, string> keyValuePairs = new Dictionary<string, string>();

        public MainWindow()
        {
            InitializeComponent();

            InitDevicePortName();
            InitShow();
        }


        private void InitDevicePortName()
        {
            using (ManagementObjectSearcher searcher = new ManagementObjectSearcher
                ("select * from Win32_PnPEntity where Name like '%(COM%'"))
            {
                var hardInfos = searcher.Get();
                foreach (var hardInfo in hardInfos)
                {
                    if (hardInfo.Properties["Name"].Value != null && hardInfo.Properties["Status"].Value != null)
                    {
                        string deviceName = hardInfo.Properties["Name"].Value.ToString();
                        string deviceStatus = hardInfo.Properties["Status"].Value.ToString();
                        keyValuePairs.Add(deviceName, deviceStatus);
                    }
                }
            }
        }

        private void InitShow()
        {
            ComListBox.ItemsSource = keyValuePairs;
        }
    }
}
